package com.zhangtai.modules.jobTask;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.zhangtai.Neusoft.service.NeuEmployeeBaseInfoService;
import com.zhangtai.Neusoft.service.NeusoftSecurityService;
import com.zhangtai.consts.CommonConstr;
import com.zhangtai.exception.QwMsg;
import com.zhangtai.modules.constVo.ContractConst;
import com.zhangtai.modules.constVo.NoticeConst;
import com.zhangtai.modules.controller.admin.*;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
//import com.zhangtai.modules.dao.ssqlDao.SsqlSalaryGoupDao;
import com.zhangtai.modules.dto.JobDto;
import com.zhangtai.modules.dto.JobLevelDto;
import com.zhangtai.modules.dto.SalaryGroupDto;
import com.zhangtai.modules.dto.SalaryPayrollUnitDto;
import com.zhangtai.modules.entity.common.Nativeplace;
import com.zhangtai.modules.entity.common.OrgEntity;
import com.zhangtai.modules.entity.contract.ContractEmployeeStatusEntity;
import com.zhangtai.modules.entity.contract.ContractMangerEntity;
import com.zhangtai.modules.entity.contract.ContractRecordEntity;
import com.zhangtai.modules.entity.contract.ProtocolPersonnelEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeRecruitmentEntity;
import com.zhangtai.modules.entity.employee.EmployeeSecurityEntity;
import com.zhangtai.modules.entity.orgin.TbOrgEhrEntity;
import com.zhangtai.modules.entity.regular.RegularBpmEntity;
import com.zhangtai.modules.entity.salary.OrgLineEntity;
import com.zhangtai.modules.entity.salary.OrgSystemEntity;
import com.zhangtai.modules.entity.salary.SalaryGroupEmployeeEntity;
import com.zhangtai.modules.entity.security.FundsRecordEntity;
import com.zhangtai.modules.entity.security.SecurityEntity;
import com.zhangtai.modules.entity.security.SecurityItemEntity;
import com.zhangtai.modules.entity.security.SecurityRecordEntity;
import com.zhangtai.modules.entity.credential.CredentialHangEntity;
import com.zhangtai.modules.jobTask.qw.Department;
import com.zhangtai.modules.jobTask.qw.QwUserEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.contract.ContractEmployeeStatusService;
import com.zhangtai.modules.service.contract.ContractMangerService;
import com.zhangtai.modules.service.contract.ContractRecordService;
import com.zhangtai.modules.service.employee.EmployeeRecruitmentService;
import com.zhangtai.modules.service.orgin.TbOrgEhrService;
import com.zhangtai.modules.service.salary.SalaryGroupEmployeeService;
import com.zhangtai.modules.vo.ContractNewVo;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.Excel.EntityUtil;
import com.zhangtai.utils.GetBeanListByExcel;
import com.zhangtai.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.record.formula.NotEqualPtg;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.zhangtai.modules.constVo.SecurityConst.CHANGE_TYPE_NORMAL;

/**
 * #企业微信通讯录
 * qx:
 * communication:
 * corpid: wwe080dd258ddb8ac7
 * corpsecret: Lo72-c7VP6Jb7LMTKPaQqeQonyhK-xmKlMXeh_-U5zQ
 * #企业微信OA打卡记录
 * check:
 * corpid: wwe080dd258ddb8ac7
 * corpsecret: o-Hi018A9LrHmgO6BGHqE3LUHfBe0DWm0Jrq7KuEd9M
 */
@RestController
@Slf4j
public class CommonJobTask {
    @Autowired
    private EmployeeInfoDao employeeInfoDao;

    @Autowired
    private QwMsg qwMsg;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private QwUserDao qwUserDao;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;

    @Autowired
    private JobController jobController;

    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;

    @Autowired
    private SecurityItemDao securityItemDao;
    @Autowired
    private EmployeeSecurityDao employeeSecurityDao;
    @Autowired
    private SecurityRecordDao securityRecordDao;
    @Autowired
    private SecurityController securityController;
    @Autowired
    private FundsRecordDao fundsRecordDao;
    @Autowired
    private SecurityDao securityDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RegularBpmDao regularBpmDao;
    //    @Autowired
//    SsqlSalaryGoupDao ssqlSalaryGoupDao;
    @Autowired
    private ContractMangerService contractMangerService;
    @Autowired
    private ContractController contractController;
    @Autowired
    private ProtocolPersonnelDao protocolPersonnelDao;
    @Autowired
    private EsignController esignController;

    private static final String GET_OAUTH_TOKEN = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxf9cc53004252c251&corpsecret=_tHc_2Cxj7aWld4WzWr5BRPDIGfxn__ERklujxYP220";

    @Autowired
    private ContractRecordService contractRecordService;
    @Autowired
    private ContractEmployeeStatusService contractEmployeeStatusService;
    @Autowired
    private NeusoftSecurityService neusoftSecurityService;
    @Autowired
    private CredentialHangDao credentialHangDao;
    @Autowired
    private CredentialInfoDao credentialInfoDao;
//    @Autowired
//    private NeuEmployeeBaseInfoService neuEmployeeBaseInfoService;

    @Autowired
    private SalaryGroupEmployeeService salaryGroupEmployeeService;
    @Autowired
    private EmployeeRecruitmentService employeeRecruitmentService;

    @Autowired
    private SalaryController salaryController;

    @Autowired
    private TbOrgEhrService orgEhrService;
    @Autowired
    private TbOrgEhrDao ehrOrgDao;

    /**
     * 每天早上8点
     * 新员工转正提醒定时器,晋升转正提醒，缓存薪资组，保存薪资组和职级
     */
//    @Scheduled(cron = "0 30 8 * * ? ")
    public void newHireRegular() {
        //查询新员工转正期小于20天未发送提醒的人
        String time = DateUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss");
        List<EmployeeInfoEntity> employeeInfoEntityList = employeeInfoDao.getTodoRegularList(time);
        for (EmployeeInfoEntity info : employeeInfoEntityList) {
            String content = "您有一条待处理新员工转正业务需要处理：" + info.getName();
            qwMsg.sendNoticeMsg("新员工转正", content, NoticeConst.TODO_TYPE_REGULAR, false, info.getOid(), info.getOid(), "新员工转正", null, info.getRegularDay(), info.getOrgId());
//             if(r.getFlag()){
            info.setIsRegularRemind(1);
            employeeInfoDao.updateById(info);
//             }
            if (!org.springframework.util.StringUtils.isEmpty(info.getRecruitmentId())) {
                EmployeeRecruitmentEntity employeeRecruitmentEntity = new EmployeeRecruitmentEntity();
                employeeRecruitmentEntity.setId(info.getRecruitmentId());
                employeeRecruitmentEntity.setIsRegularRemind(1);
                employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
            }
        }
        sendPromotionRegularNotice();//晋升转正提醒
//        findAllsalaryGroupFromSsql();//缓存薪资组
//        salary();//保存薪资组和职级
        doContract();//合同续签
    }

    /**
     * 签署协议服务日期到期定时修改状态
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateProtocol() {
        //查询新签署协议服务日期小于当天的并且状态不为 3 、4
        String time = DateUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss");
        List<ProtocolPersonnelEntity> protocolPersonnelEntityList = protocolPersonnelDao.selectList(new QueryWrapper<ProtocolPersonnelEntity>().lt("service_end_time", time).eq("status", 2));
        for (ProtocolPersonnelEntity protocolPersonnelEntity : protocolPersonnelEntityList) {
            protocolPersonnelEntity.setStatus(3);
            protocolPersonnelEntity.setConsummationTime(new Date());
            protocolPersonnelDao.updateById(protocolPersonnelEntity);
        }
    }


    /**
     * 获取所有企微账号 ,全量更新到数据库，每天凌晨2点半执行一次
     *
     * @return
     * @Scheduled(cron = " ")
     */
    @GetMapping("/getAllQWUser")
    @ApiOperation("获取企业微信的部门,每天进行一次自动同步")
    @Scheduled(cron = "0 0 0 1/1 * ?  ")
    public String getAllQWUser() {
        log.info("开始执行获取所有企微用户定时任务");
        String acUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwe080dd258ddb8ac7&corpsecret=Lo72-c7VP6Jb7LMTKPaQqeQonyhK-xmKlMXeh_-U5zQ";
        JSONObject forObject = restTemplate.getForObject(acUrl, JSONObject.class);
        String access_token = (String) forObject.get("access_token");
        JSONObject jsonObject = restTemplate.getForObject("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + access_token, JSONObject.class);
        JSONArray jsonarr = jsonObject.getJSONArray("department");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=" + access_token + "&department_id=%s&fetch_child=0";
        //根据部门列表获取到部门列表
        List<Map> list = new ArrayList<>();
        List<Map> userlist = null;
        for (Object o : jsonarr) {
            TbOrgEhrEntity tbOrgEhrEntity = new TbOrgEhrEntity();
            String s = JSON.toJSONString(o);
            Department department = JSON.parseObject(s, Department.class);
            if (ehrOrgDao.selectById(department.getId()) == null) {
                tbOrgEhrEntity.setType("部门");
                tbOrgEhrEntity.setCategory(1);
                tbOrgEhrEntity.setOrgid(department.getId());
                tbOrgEhrEntity.setParrorgid(department.getParentid());
                tbOrgEhrEntity.setOrgname(department.getName());
                tbOrgEhrEntity.setSort(department.getOrder());
                orgEhrService.save(tbOrgEhrEntity);
            }
            //获取部门成员详情
            String format = String.format(url, department.getId() + "");
            JSONObject object = restTemplate.getForObject(format, JSONObject.class);
            userlist = (List<Map>) object.get("userlist");
            list.addAll(userlist);
        }

        HashSet<QwUserEntity> dayEntityHashSet = new HashSet<>();

        for (Map map : list) {
            String s = JSON.toJSONString(map);
            QwUserEntity qwUser = JSON.parseObject(s, QwUserEntity.class);
            if (qwUser.getStatus().equals(1) && qwUser.getStatus().equals(1)) {
                String name = qwUser.getName();
                if (name.contains("-")) {
                    String[] split = name.split("-");
                    name = split[split.length - 1];
                    qwUser.setName(name);
                }
                String orgid=null;
                int[] department = qwUser.getDepartment();
                for (int o : department) {
                     orgid = Integer.toString(o);
                    orgid+="";
                }
                qwUser.setOrgids(orgid);
                dayEntityHashSet.add(qwUser);
            }
        }
        for (QwUserEntity qwUserEntity : dayEntityHashSet) {
            String mobile = qwUserEntity.getMobile();
            String userid = qwUserEntity.getUserid();
            //默认考情规则为1
            qwUserEntity.setCheckRuleId(1);
//            List<String> userCodeByMobile = jobDaoMssql.findUserCodeByMobile(mobile);
//            if (CollectionUtils.isEmpty(userCodeByMobile)) {
//                userCodeByMobile = jobDaoMssql.findUserCodeByUserId(userid);
//            }
//            if (!CollectionUtils.isEmpty(userCodeByMobile)) {
//                qwUserEntity.setUserCode(userCodeByMobile.get(0));
//            }
            List<QwUserEntity> userid1 = qwUserDao.selectList(new QueryWrapper<QwUserEntity>().eq("userid", userid));
            if (userid1.size()==0){
                qwUserDao.insert(qwUserEntity);
            }
        }
        return null;

    }



//    /**
//     * 待入职提醒
//     */
//    @Scheduled(cron = "0 30 0 * * ?")
//    public void newEntry(){
//        ArrayList<Integer> integers = new ArrayList<>();//仅展示0:新员工，1：复职员工
//        integers.add(0);
//        integers.add(1);
//        Date date = new Date();
//        String startTime = DateUtils.format(date,"yyyy-MM-dd")+" 00:00:00";
//        String endTime = DateUtils.format(date,"yyyy-MM-dd")+" 23:59:59";
//        //status:员工录用状态：0:新建 ，1：填写完以保存 2：bpm待审批，3：审批完成，正式录用，4：作废
//        List<EmployeeInfoEntity> employeeInfoEntities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().in("is_reinstate", integers).eq("is_hire_done", 0)
//                .eq("is_delete", 0).between("hiredate",startTime,endTime));
//        for(EmployeeInfoEntity employeeInfoEntity:employeeInfoEntities){
//            Long oid = employeeInfoEntity.getOid();
//            String name = employeeInfoEntity.getName();
//            String principalUserCode = employeeInfoEntity.getPrincipalUserCode(); //负责人工号
//            if (StringUtils.isEmpty(principalUserCode)){
//                throw new RException("负责人工号为空");
//            }
//            String content = "您有一条入职流程需要发起：" + name;
//            //发送企微信息以及入职待办通知
//            qwMsg.sendNoticeMsg("入职待办",content,TodoConst.PRE_ENTRY,false,oid,employeeInfoEntity.getOid(),"入职",employeeInfoEntity.getPrincipalUserCode(),null);
//        }
//    }

    /**
     * 同步sqlserver主数据数据，每小时同步一次
     */
//    @GetMapping("/orgAsync")
    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void org() {
        List<TbOrgEhrEntity> allOrg = baseMssqlService.findAllOrg();
        //TODO
        /*if(ObjectUtils.isEmpty(jobController.orgAllChildrenMap)){
            jobController.orgAllChildrenMap = new HashMap<>();
        }*/
        /*  List<Map<String, Object>> list = baseMssqlService.finOrgByPid(allOrg, -1l, new ArrayList<Long>());*/
//        缓存组织机构map
        HashMap<Long, String> orgMap = new HashMap<>();
       /* for (OrgEntity orgEntity : allOrg) {
            orgMap.put(orgEntity.getId(), orgEntity.getName());
        }*/
        jobController.orgMap = orgMap;
//        redisTemplate.boundHashOps(CommonConstr.ORG_MAP).put(CommonConstr.ORG_ITEM,orgMap);  //缓存组织机构树

        //所有岗位
        List<JobDto> allJob = baseMssqlService.findAllJob();
        HashMap<Long, String> jobMap = new HashMap<>();
        for (JobDto jobDto : allJob) {
            jobMap.put(jobDto.getCoidassignedjob(), jobDto.getCname());
        }
        jobController.jobMap = jobMap;
//        redisTemplate.boundHashOps(CommonConstr.JOB_MAP).put(CommonConstr.JOB_ITEM,jobMap); //缓存岗位map

//缓存职级map
        List<JobLevelDto> jobLevels = baseMssqlService.findJobLevel();
        HashMap<Long, String> jobLevelMap = new HashMap<>();
        HashMap<Long, String> jobLevelCodeMap = new HashMap<>();
        for (JobLevelDto jobLevel : jobLevels) {
            jobLevelMap.put(jobLevel.getId(), jobLevel.getName());
            jobLevelCodeMap.put(jobLevel.getId(), jobLevel.getCode());
        }
        jobController.jobLevelMap = jobLevelMap;
        jobController.jobLevelCodeMap = jobLevelCodeMap;

        //缓存职级实体map
        HashMap<Long, JobLevelDto> jobLevelEntityMap = new HashMap<>();
        for (JobLevelDto jobLevel : jobLevels) {
            jobLevelEntityMap.put(jobLevel.getId(), jobLevel);
        }
        jobController.jobLevelEntityMap = jobLevelEntityMap;

//        redisTemplate.boundHashOps(CommonConstr.JOB_LEVEL_MAP).put(CommonConstr.JOB_LEVEL_ITEM,jobLevelMap); //缓存岗位map

//        体系
        List<OrgSystemEntity> allOrgSystemEntity = baseMssqlService.findAllOrgSystemEntity();
        HashMap<Long, String> systemMap = new HashMap<>();
        for (OrgSystemEntity orgSystemEntity : allOrgSystemEntity) {
            systemMap.put(orgSystemEntity.getId(), orgSystemEntity.getName());
        }
        jobController.systemMap = systemMap;

//        条线
        List<OrgLineEntity> allOrgLineEntity = baseMssqlService.findAllOrgLineEntity();
        HashMap<Long, String> lineMap = new HashMap<>();
        for (OrgLineEntity orgLineEntity : allOrgLineEntity) {
            lineMap.put(orgLineEntity.getId(), orgLineEntity.getName());
        }
        jobController.lineMap = lineMap;

        System.out.println("定时任务开始执行");
        asynBase();// 同步籍贯树、组织机构树、职级、条线、体系、招聘网站 到redis

        jobController.getBase(); //更新体系条线

        gettoken();//获取企微token


    }


    public String gettoken() {
        /**
         *
         * 获取企微登录的access_token
         * @return
         */
        JSONObject forObject = restTemplate.getForObject(GET_OAUTH_TOKEN, JSONObject.class);

//        获取oauthtoken
        String access_token = forObject.getString("access_token");

        redisTemplate.boundValueOps(CommonConstr.OAUTH_ACCESS_TOKEN_KEY).set(access_token, 70, TimeUnit.MINUTES);
        return access_token;
    }


    /**
     * 民族 国家
     */
//    @GetMapping("/nationAndCity")
//    public void nationAndCity() {
//
//        List<JSONObject> nationality = jobDaoMssql.getNationality();
//        HashMap<String, String> hashMap = new HashMap<>();
//        for (JSONObject jsonObject : nationality) {
//            String c_code = jsonObject.getString("C_CODE");
//            String c_name = jsonObject.getString("C_NAME");
//            hashMap.put(c_code, c_name);
//        }
//        jobController.nationality = hashMap;
//        HashMap<Long, String> longStringHashMap = new HashMap<>();
//        List<Nativeplace> allNativeplace = baseMssqlService.findAllNativeplace();
//        for (Nativeplace nativeplace : allNativeplace) {
//            Long id = nativeplace.getId();
//            String name = nativeplace.getName();
//            longStringHashMap.put(id, name);
//        }
//        jobController.nativeplace = longStringHashMap;
//
//
//    }

    /**
     * 缓存工资组  和职级
     */
//    @Scheduled(cron = "0 30 2 * * ? ")
//    public void salary() {
//        List<SalaryGroupDto> allsalaryGroupFromSsql = jobDaoMssql.findAllsalaryGroupFromSsql2();
//        HashMap<Long, SalaryGroupDto> longSalaryGroupDtoHashMap = new HashMap<>();
//        for (SalaryGroupDto salaryGroupDto : allsalaryGroupFromSsql) {
//            Long coidGroup = salaryGroupDto.getCoidGroup();
//            longSalaryGroupDtoHashMap.put(coidGroup, salaryGroupDto);
//
//        }
//        jobController.salaryGroupDtoMap = longSalaryGroupDtoHashMap;
//        List<Map<String, Object>> Map = ssqlSalaryGoupDao.getSalaryUnit();
//        List<SalaryPayrollUnitDto> salaryGroupDtoArrayList = EntityUtil.ListMapToListObj(Map, SalaryPayrollUnitDto.class);
//        Map<String, String> company = new HashMap<>();
//        HashMap<Long, SalaryPayrollUnitDto> SalaryPayrollUnitMap = new HashMap<>();
//        for (SalaryPayrollUnitDto salaryPayrollUnitDto : salaryGroupDtoArrayList) {
//            Long coidOrgunit = salaryPayrollUnitDto.getCoidOrgunit();
//            SalaryPayrollUnitMap.put(coidOrgunit, salaryPayrollUnitDto);
//            company.put(salaryPayrollUnitDto.getCname(), salaryPayrollUnitDto.getCoidOrgunit().toString());
//
//        }
//        jobController.SalaryPayrollUnitMap = SalaryPayrollUnitMap;
//
//
//        List<JobLevelDto> jobLevel = baseMssqlService.findJobLevel(); //职级
//        HashMap<String, Long> stringUtilsLongHashMap = new HashMap<>();
//        for (JobLevelDto jobLevelDto : jobLevel) {
//            String name = jobLevelDto.getName();
//            Long id = jobLevelDto.getId();
//            stringUtilsLongHashMap.put(name, id);
//        }
//        jobController.jobLevel = stringUtilsLongHashMap;
//        jobController.company = company;
//
//    }

    //    @GetMapping("/securityAsync")
//    @Scheduled(cron = "0 0/30 * * * ?")
    public void security() {
        List<SecurityItemEntity> securityItemEntityList = securityItemDao.selectList(new QueryWrapper<SecurityItemEntity>().orderByDesc("security_id"));
        Map<Integer, SecurityItemEntity> itemMap = new HashMap<>();
        Map<Long, Map<Integer, SecurityItemEntity>> securityMap = new HashMap<>();
        Long beforeSecurityId = null;
        if (!CollectionUtils.isEmpty(securityItemEntityList)) {
            int i = 0;
            for (SecurityItemEntity item : securityItemEntityList) {
                if (!item.getSecurityId().equals(beforeSecurityId)) {
                    if (beforeSecurityId != null) {
                        securityMap.put(beforeSecurityId, itemMap);
                        itemMap = new HashMap<>();
                        itemMap.put(item.getSecurityType(), item);
                    } else {
                        itemMap.put(item.getSecurityType(), item);
                    }
                } else {
                    if (i != securityItemEntityList.size() - 1) {
                        itemMap.put(item.getSecurityType(), item);
                    } else {
                        itemMap.put(item.getSecurityType(), item);
                        securityMap.put(beforeSecurityId, itemMap);
                    }
                }
                beforeSecurityId = item.getSecurityId();
                i++;
            }
        }
        jobController.securityMap = securityMap;
        //缓存中是否存在方案map数据
        if (ObjectUtils.isEmpty(jobController.sMap)) {
            List<SecurityEntity> securityEntities = securityDao.selectList(new QueryWrapper<SecurityEntity>().eq("is_delete", 0));
            Map<Long, SecurityEntity> map = new HashMap<>();
            for (SecurityEntity securityEntity : securityEntities) {
                map.put(securityEntity.getSecurityId(), securityEntity);
            }
            jobController.sMap = map;
        }

//        redisTemplate.boundHashOps(CommonConstr.SECURITY_MAP).put(CommonConstr.SECURITY_ITEM,securityMap);
    }

    /**
     * 缴费记录定时器
     */
    //@GetMapping("/testCreateNewSecurityRecord")
    @Scheduled(cron = "0 30 1 2 * ? ")
    public void createNewSecurityRecord() {
        String startMonth = DateUtils.getBeginDayOfMonth();
        String endMonth = DateUtils.getLastDayOfMonth();
//        String startMonth = "2020-10-01 00:00:00";
//        String endMonth = "2020-11-01 00:00:00";
        List<EmployeeSecurityEntity> userSecurityEntities = employeeSecurityDao.selectList(new QueryWrapper<EmployeeSecurityEntity>().eq("is_delete", 0));
        //查看是否有缴费月为当月的处理中、完结的社保缴费记录
        List<SecurityRecordEntity> securityRecords = securityRecordDao.selectList(new QueryWrapper<SecurityRecordEntity>().between("operate_time", startMonth, endMonth).ne("is_check", 1));
        List<FundsRecordEntity> fundsRecords = fundsRecordDao.selectList(new QueryWrapper<FundsRecordEntity>().between("operate_time", startMonth, endMonth).ne("is_check", 1));
        String securityOids = "";
        String fundsOids = "";
//        Date operateTime = new Date();
        Date operateTime = DateUtils.parseDateYMD(startMonth);
        for (SecurityRecordEntity record : securityRecords) {
            securityOids += record.getOid() + ",";
        }
        for (FundsRecordEntity record : fundsRecords) {
            fundsOids += record.getOid() + ",";
        }
        for (EmployeeSecurityEntity employeeSecurityEntity : userSecurityEntities) {
            //已处理过的社保人员缴费记录，跳过
            if (!StringUtils.isEmpty(securityOids) && securityOids.indexOf(employeeSecurityEntity.getOid().toString()) >= 0) {

            } else {
                //添加社保缴费记录
                if (!ObjectUtils.isEmpty(employeeSecurityEntity.getSecurityId())) {
                    SecurityEntity securityEntity = jobController.sMap.get(employeeSecurityEntity.getSecurityId());
                    SecurityRecordEntity securityRecordEntity = new SecurityRecordEntity();
                    securityRecordEntity.setCreateTime(new Date());
                    securityRecordEntity.setOperateTime(operateTime);
                    securityRecordEntity.setOid(employeeSecurityEntity.getOid());
                    securityRecordEntity.setUnitName(securityEntity.getUnitName());
                    securityRecordEntity.setCityName(securityEntity.getCityName());
                    securityRecordEntity.setSecurityId(securityEntity.getSecurityId());
                    securityController.addSecurityRecord(employeeSecurityEntity.getOid(), null, null, securityRecordEntity, operateTime, CHANGE_TYPE_NORMAL);
                }
            }
            //已处理过的公积金人员缴费记录，跳过
            if (!StringUtils.isEmpty(fundsOids) && fundsOids.indexOf(employeeSecurityEntity.getOid().toString()) >= 0) {

            } else {
                //添加公积金缴费记录
                if (!ObjectUtils.isEmpty(employeeSecurityEntity.getFundsId())) {
                    SecurityEntity securityEntity = jobController.sMap.get(employeeSecurityEntity.getFundsId());
                    FundsRecordEntity fundsRecordEntity = new FundsRecordEntity();
                    fundsRecordEntity.setCreateTime(new Date());
                    fundsRecordEntity.setOperateTime(operateTime);
                    fundsRecordEntity.setOid(employeeSecurityEntity.getOid());
                    fundsRecordEntity.setUnitName(securityEntity.getUnitName());
                    fundsRecordEntity.setCityName(securityEntity.getCityName());
                    fundsRecordEntity.setSecurityId(securityEntity.getSecurityId());
                    securityController.addFundsRecord(employeeSecurityEntity.getOid(), null, null, fundsRecordEntity, operateTime, CHANGE_TYPE_NORMAL);
                }
            }
        }
    }

    /**
     * 晋升转正提醒定时器
     */
    public void sendPromotionRegularNotice() {
        //查询员工自助端管理晋升观察期小于30天未发送提醒的人
        String time = DateUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss");
        List<RegularBpmEntity> list = regularBpmDao.sendRegularNotice(time);
        for (RegularBpmEntity entity : list) {
            String title = "您的管理晋级考察即将结束请发起转正申请";
            qwMsg.sendNoticeMsg("管理晋升转正", title, NoticeConst.MSG_TYPE_PROMOTION_REGULAR, false, entity.getOid(), entity.getId(), null, entity.getCode(), entity.getRegularDay(), null);
//           if(r.getFlag()){
            entity.setIsRegularRemind(1);
            regularBpmDao.updateById(entity);
//           }
        }
    }

    /**
     * 每月1号同步补贴到ehr
     */
//    @Scheduled(cron = "0 1 0 1 * ?")
//    public void saveSubsidy() {
//        neuEmployeeBaseInfoService.getComputerSubsidy();
//    }

    /**
     * 每天0点检查离职人员补贴设置为失效
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void updateComputerSubsidy() {
        salaryController.updateComputerSubsidy();
    }


    /**
     * 整体缓存薪资组
     */
//    public void findAllsalaryGroupFromSsql() {
//        List<SalaryGroupDto> allsalaryGroupFromSsql = jobDaoMssql.findAllsalaryGroupFromSsql2();
//        jobController.salaryGroupMap.put("salaryGroupMap", allsalaryGroupFromSsql);
//    }

    /**
     * 同步薪酬组和员工的对应关系，每小时一次
     */
//    @Scheduled(cron = "0 0 0/1 * * ?")
//    @GetMapping("/syncAllEmployeeSalaryGroup")
//    public void syncAllEmployeeSalaryGroup() {
//        Date date = DateUtils.addDateDays(new Date(), -1);
//        String dateString = DateUtils.format(date, DateUtils.DATE_PATTERN) + " 00:00:00";
//        List<SalaryGroupEmployeeEntity> employeeSalaryGroupList = jobDaoMssql.getEmployeeSalaryGroup(dateString);
//        for (SalaryGroupEmployeeEntity employeeSalaryGroup : employeeSalaryGroupList) {
//            salaryGroupEmployeeService.saveOrUpdateE(employeeSalaryGroup);
//        }
//    }


    /**
     * 合同续签
     */
//    @GetMapping("/doContract")
    @Scheduled(cron = "0 30 1 * * ?")
    public void doContract() {
        String date = DateUtils.format(new Date(), "yyyy-MM-dd") + " 00:00:00";
//        String date = "2023-10-29 00:00:00";
        List<ContractMangerEntity> drawToRenew = contractMangerService.getDrawToRenewList(date);
        List<ContractMangerEntity> drawToClose = contractMangerService.getDrawToCloseList(date);
        //合同到期
        for (ContractMangerEntity close : drawToClose) {
            close.setContractStatus(ContractConst.EMPLOYEE_STATUS_PASTED);
            contractMangerService.updateByIdE(close);
            ContractEmployeeStatusEntity employeeStatusEntity = contractEmployeeStatusService.getByKindAndOid(close.getOid(), 1);
            employeeStatusEntity.setContractStatus(ContractConst.EMPLOYEE_STATUS_PASTED);
            ContractRecordEntity recordEntity = new ContractRecordEntity();
            recordEntity.setId(employeeStatusEntity.getRecordId());
            recordEntity.setStatus(ContractConst.EMPLOYEE_STATUS_PASTED);
            recordEntity.setEndType(ContractConst.CONTRACT_END_TYPE_FINISHED);
            recordEntity.setEndTime(employeeStatusEntity.getContractEndDate());
            contractRecordService.updateByIdE(recordEntity);
            contractMangerService.updateByIdE(close);
            contractEmployeeStatusService.updateByIdE(employeeStatusEntity);
        }
        //待续约的合同
        if (!CollectionUtils.isEmpty(drawToRenew)) {
            ContractNewVo vo = new ContractNewVo();
            vo.setType(ContractConst.CONTRACT_TYPE_RENEW);
            vo.setOperateType(ContractConst.CONTRACT_OPERATE_RENEW);
            for (ContractMangerEntity renew : drawToRenew) {
                vo.setOid(renew.getOid());
                vo.setCompanyId(renew.getEmployerCompanyId());
                vo.setCompanyName(renew.getEmployerCompany());
                vo.setContractBeginDate(DateUtils.addDateDays(renew.getContractEndDate(), 1));
                vo.setContractTimeType(renew.getContractTimeType());
                vo.setRelateId(renew.getId());
                contractController.saveNewContract(vo);
                renew.setIsRenew(1);
                contractMangerService.updateByIdE(renew);
            }
        }

    }

    /**
     * ehr合同数据同步 每个月 1号/15号执行一次
     */
    // @Scheduled(cron = "0 30 0 1,15,27 * ?")
    public void asyncEhrContract() {
        contractController.getEhrContractRecord();
    }

    /**
     * 定期检查合同是否回调成功，如果不成功则作补偿,每20分钟补偿一次
     *
     * @throws Exception
     */

    @GetMapping("/checkContract")
    @Scheduled(cron = "0 0/20 * * * ?")
    public void checkContract() throws Exception {
        esignController.checkContractStatus();
        esignController.checkProtocolContractStatus();
        esignController.checkCertificate();
    }


//    @Scheduled(cron = "0 30 23 * * ?")
//    public void asyncMemberInfo() {
//        String date = DateUtils.format(new Date());
//        String startTime = date + " 00:00:00";
//        String endTime = date + " 23:59:59";
//        List<String> codeList = jobDaoMssql.getEmployeeChangeDaily(startTime, endTime);
//        for (String code : codeList) {
//            EmployeeInfoEntity infoEntity = jobDaoMssql.findEmpByCode(code);
//            List<EmployeeInfoEntity> entityList = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", code));
//            for (EmployeeInfoEntity entity : entityList) {
//                entity.setUnitId(infoEntity.getUnitId());
//                entity.setOrgId(infoEntity.getOrgId());
//                entity.setJobId(infoEntity.getJobId());
//                entity.setJobLevelId(ObjectUtils.isEmpty(infoEntity.getManagementJoblevelId()) ? infoEntity.getManagementJoblevelId() : infoEntity.getProfessionJoblevelId());
//                employeeInfoDao.updateById(entity);
//            }
//        }
//    }


    /**
     * 挂证补贴定时器
     */
    @Scheduled(cron = "0 30 0 1 * ?")
    public void uploadCredential() {
        List<CredentialHangEntity> hangEntityList = credentialHangDao.selectList(new QueryWrapper<CredentialHangEntity>().eq("is_delete", 0).eq("status", 2));
        neusoftSecurityService.uploadCredential(hangEntityList);
    }

    @Scheduled(cron = "0 30 7 * * ?")
    public void pastCredential() {
        String time = DateUtils.format(new Date(), "yyyy-MM-dd hh:mm:ss");
        credentialInfoDao.updateCredentialPast(time);
    }

    /**
     * 同步籍贯树、组织机构树、职级、条线、体系、招聘网站
     */
    public void asynBase() {
        JSONObject jsonObject = new JSONObject();

//        籍贯树
        List<Nativeplace> allNativePlace = baseMssqlService.findAllNativeplace();
        List<Map<String, Object>> nativePlace = baseMssqlService.findNativePlaceByPid(allNativePlace, -1l);
        jsonObject.put("nativePlace", nativePlace);

//            组织机构树
        List<TbOrgEhrEntity> entityList = baseMssqlService.findAllOrg();
        jsonObject.put("orgList", entityList);
        // List<Map<String, Object>> list = baseMssqlService.finOrgByPid(entityList, -1l, new ArrayList<Long>());
        List<TbOrgEhrEntity> list = baseMssqlService.orgListTree();
        System.out.println(list);
        jsonObject.put("orgTree", list);

//职级
        List<JobLevelDto> jobLevel = baseMssqlService.findJobLevel();
//            redisTemplate.boundHashOps("JobLevel").put("level",jobLevel);
        jsonObject.put("jobLevel", jobLevel);

//            条线
        List<OrgLineEntity> allOrgLineEntity = baseMssqlService.findAllOrgLineEntity();
        jsonObject.put("orgLine", allOrgLineEntity);

//            体系
        List<OrgSystemEntity> allOrgSystemEntity = baseMssqlService.findAllOrgSystemEntity();
        jsonObject.put("orgSystem", allOrgSystemEntity);


//        招聘网站
        List<JSONObject> recruitWeb = baseMssqlService.findRecruitWeb();
        jsonObject.put("recruitWeb", recruitWeb);

        redisTemplate.boundHashOps("GETBASEITEM").put("item", jsonObject);
    }

    /**
     * @return
     * @Description: 定时同步解除合同信息到ehr
     * @params 0 30 3 * * ?
     * @Author: czw
     * @CreateDate: 2021/3/30 15:31
     */
//    @Scheduled(cron = "0 30 3 * * ?")
//    public void asynRelieveContract() {
//        neuEmployeeBaseInfoService.asynRelieveContract();
//    }
    public static void main(String[] args) throws Exception {

        String[] cellKey = {"code", "name"};
        List<RegularBpmEntity> beanList = GetBeanListByExcel.getBeanList("/Users/lishenhong/Desktop/test.xls", cellKey, RegularBpmEntity.class);
        for (RegularBpmEntity regularBpmEntity : beanList) {
            System.out.println(regularBpmEntity);
        }
    }

}
